// 本模块是为了提供围绕任务及通知的一系列功能而设计

const moment = require("moment");
const axios = require("axios");

const rds = require("./rds");
const tutils = require("./tutils");
const logger = require("./logger");
const wework = require('./wework');

// 状态数组
const taskStatusArray = [
    "pending",
    "inProgress",
    "completed",
    "finished",
    "cancelled",
    "failed",
    "onHold",
    "assigned",
    "approved",
    "rejected",
    "overdue",
];
const taskStatusDescriptions = {
    pending: "待处理（任务已创建但尚未开始执行）",
    inProgress: "进行中（任务正在执行过程中）",
    completed: "已完成（任务已成功完成）",
    finished: "已完成（任务已成功完成）",
    cancelled: "已取消（任务由于某种原因被取消，不再执行）",
    failed: "已失败（任务执行过程中发生错误或失败）",
    onHold: "已暂停（任务暂时停止执行，但可能会在将来恢复）",
    assigned: "已分配（任务已经被分配给相应的执行者，但尚未开始执行）",
    approved: "已批准（任务已经通过审核或获得批准，可以执行）",
    rejected: "已拒绝（任务被拒绝执行或审核未通过）",
    overdue: "已逾期（任务的截止日期已过，但尚未完成）",
};
const taskStatusInfos = {
    pending:
        '<span style="color:#ff7f50;" title="任务已创建但尚未开始执行">待处理</span>',
    inProgress:
        '<span style="color:#0f4c81;" title="任务正在执行过程中">进行中</span>',
    completed:
        '<span style="color:#88b04b;" title="任务已成功完成"> 已完成</span>',
    finished:
        '<span style="color:#88b04b;" title="任务已成功完成"> 已完成</span>',
    cancelled:
        '<span style="color:#c1c1c1;" title="任务由于某种原因被取消，不再执行">已取消</span>',
    failed: '<span style="color:#c1c1c1;" title="任务执行过程中发生错误或失败">已失败</span>',
    onHold: '<span style="color:#ffd700;" title="任务暂时停止执行，但可能会在将来恢复">已暂停</span>',
    assigned:
        '<span style="color:#0f4c81;" title="任务已经被分配给相应的执行者，但尚未开始执行">已分配</span>',
    approved:
        '<span style="color:#0f4c81;" title="任务已经通过审核或获得批准，可以执行">已批准</span>',
    rejected:
        '<span style="color:#c1c1c1;" title="任务被拒绝执行或审核未通过">已拒绝</span>',
    overdue:
        '<span style="color:#ff0000;" title="任务的截止日期已过，但尚未完成">已逾期</span>',
};
const taskStatusActions = {
    pending: "待处理",
    inProgress: "进行中",
    completed: "已完成",
    finished: "已完成",
    cancelled: "已取消",
    failed: "已失败",
    onHold: "已暂停",
    assigned: "已分配",
    approved: "已批准",
    rejected: "已拒绝",
    overdue: "已逾期",
};

const idQuery = `
    SELECT t.id as id, t.code, t.assignee_uid as uid, COALESCE(u.real_name,'') as user_name, t.title, t.description, t.entry, t.status 
    FROM tutem_mall.tasks t
    LEFT JOIN tutem_mall.eb_user u ON t.assignee_uid = u.uid
    LEFT JOIN tutem_mall.eb_wechat_user w ON t.assignee_uid = w.uid
    WHERE t.id = ?`;

async function assignTask(
    assignee_type = "repID",
    assignee_id = 2,
    task_code = "tmall_registration_followup",
    task_title = "请提示客户有新荐用户访问，然后更新用户信息",
    channels = "Wework",
    entry = "https://totemlife.cn/apps/crm/create-user-profile?uid=1",
    description = "R#2-DXF的T1会员C#6推荐新用户U#18888进入了MTA平台",
    status = "pending"
) {
    let publisher_uid = 0;
    let assignee_uid = 0;
    switch (assignee_type) {
        case ("rep_id", "repID"):
            const [repIdResults] = await rds.query(
                "SELECT uid FROM eb_rep WHERE id = ?",
                [assignee_id]
            );
            assignee_uid = repIdResults[0]?.uid || 0;
            break;
        case "repCODE":
            const [repCodeResults] = await rds.query(
                "SELECT uid FROM eb_rep WHERE code = ?",
                [assignee_id]
            );
            assignee_uid = repCodeResults[0]?.uid || 0;
            break;
        case ("aid", "adminID"):
            const [aidResults] = await rds.query(
                "SELECT uid FROM eb_rep WHERE aid = ?",
                [assignee_id]
            );
            assignee_uid = aidResults[0]?.uid || 0;
            break;
        case ("uid", "totemUID"):
        default: // include 'uid'
            assignee_uid = assignee_id;
            break;
    }

    const content = {
        task_code,
        publisher_uid,
        assignee_uid,
        channels,
        task_title,
        description,
        entry,
        status,
    };
    const taskId = (await insertTask(content)) || 0;

    if (taskId) {
        const appendText = `&task_id=${taskId}`;
        const updateResult = await updateTaskEntry(taskId, appendText); // 调用更新任务 entry 的函数
        result = updateResult ? true : false;
        channels.split(" ").forEach(async (channel) => {
            const content =
                channel === "Wework"
                    ? await genTaskMarkdown(taskId)
                    : await genTaskText(taskId);
            let notified = false;
            if (channel === "Wework")
                notified = notifyWework(assignee_uid, content);
            if (channel === "Xiaoteng")
                notified = notifyXiaoteng(assignee_uid, content);
            if (channel === "Tutu")
                notified = notifyTutu(assignee_uid, content);
            if (notified) {
                const updateQuery = `update tutem_mall.tasks set notified_count = notified_count + 1 where id = ${taskId}`;
                // 更新通知计数
                // 在数据库中更新通知计数
            }
        });
    }

    return taskId;
}

async function updateTaskEntry(taskId, appendText) {
    const updateQuery =
        "UPDATE tasks SET entry = CONCAT(entry, ?) WHERE id = ?";

    try {
        await rds.query(updateQuery, [appendText, taskId]);
        return true; // 返回成功标志
    } catch (error) {
        console.error("Error updating task entry:", error);
        return false; // 处理更新错误的情况
    }
}

async function insertTask(content) {
    const {
        task_code,
        publisher_uid,
        assignee_uid,
        channels,
        task_title,
        description,
        entry,
        status,
    } = content;
    const query = `
        INSERT INTO tasks (code, publisher_uid, assignee_uid, notification_channels, title, description, entry, status)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        `;
    const params = [
        task_code,
        publisher_uid,
        assignee_uid,
        channels,
        task_title,
        description,
        entry,
        status,
    ];
    try {
        const [result] = await rds.query(query, params);
        return result.insertId; // 返回插入的 taskId
    } catch (error) {
        console.error("Error inserting task:", error);
        return null; // 处理插入错误的情况
    }
}

async function genTaskMarkdown(taskId) {
    try {
        const [tasks] = await rds.query(idQuery, [taskId]);

        if (tasks.length === 0) return null;

        const { id, code, uid, user_name, title, description, entry, status } =
            tasks[0];

        let content = `#### U${uid} ${user_name} 有新任务T${id}\n`;
        content += `事件： ${code}\n`;
        content += `说明： <font color='comment'>${description}</font>\n`;
        content += `任务： <font color='info'>${title}</font>\n`;
        content += `状态： <font color='warning'>${status}</font>\n`;
        content += `入口： [【点这里完成任务】](${entry})\n`;
        content += `<font color='comment'>日事日清，每日精进</font>`;

        return content;
    } catch (error) {
        console.error(error);
        return null;
    }
}

async function genTaskText(taskId) {
    try {
        const [tasks] = await rds.query(idQuery, [taskId]);

        if (tasks.length === 0) return null;

        const { id, code, uid, user_name, title, description, entry, status } =
            tasks[0];

        let content = `U#${uid} ${user_name} 有新任务T#${id}\n`;
        content += `事件： ${code}\n`;
        content += `说明： ${description}\n`;
        content += `任务： ${title}\n`;
        content += `状态： ${status}\n`;
        content += `入口： 点下方链接完成任务\n`;
        content += ` ${entry} \n`;
        content += `日事日清，每日精进`;

        return content;
    } catch (error) {
        console.error(error);
        return null;
    }
}

async function notifyBot(bot = "Xiaoteng", content, mentioned_list = ["@all"]) {
    botUrlMap = { Xiaoteng: "BOT_Xiaoteng", Tutu: "BOT_Tutu" };
    const url = process.env[botUrlMap[bot]];
    if (!url) return false;

    const data = {
        msgtype: "text",
        text: { content: content, mentioned_list: mentioned_list },
    };

    try {
        const response = await axios.post(url, data, {
            headers: { "Content-Type": "application/json" },
        });
        return response.data.errcode === 0;
    } catch (error) {
        console.error("Error sending notification:", error);
        return false;
    }
}

async function notifyWework(uid, content, agentid = 1000026) {
    return wework.sendMessage(uid, content, agentid);
}

async function notifyTutu(uid, content) {
    const touser = await wework.getUserid(uid);
    const mentioned = touser === "" ? ["@all"] : [touser];
    return notifyBot("Tutu", content, mentioned);
}

async function notifyXiaoteng(uid, content) {
    const touser = await wework.getUserid(uid);
    const mentioned = touser === "" ? ["@all"] : [touser];
    return notifyBot("Xiaoteng", content, mentioned);
}

async function notifyUserAction(uid, info, title = "ACTION NOTICE") {
    const sql = `select * from tutem_mall.eb_user where uid = ${uid}`;
    const [rows] = await rds.query(sql);
    let ret = false; //推送给rep是否成功
    if (rows[0]) {
        const user = rows[0];
        user.type = `P${user.is_promoter}T${user.promoter_type}`;
        user.name = user.real_name;
        const notice = `#### U${uid} ${title}\n${user.name} ${user.type} C${user.spread_uid}R${user.rep_uid}\n${info}`;
        logger.info(title, notice.replace(/\n/g, " "));
        if (user.rep_uid > 0 && user.rep_uid != user.uid) {
            ret = await notifyWework(user.rep_uid, notice, 1000026);
        }
    }
    return ret;
}

async function recordUserAction(uid, peer_uid, path, action, options_str) {
    // 定义查询条件
    const dayBegin = new Date(); // 设置查询开始时间，例如当天开始
    const dayEnd = new Date(); // 设置查询结束时间，例如当天结束
    dayBegin.setHours(0, 0, 0); //设置为当天开始
    dayEnd.setHours(23, 59, 59); // 设置为当天的最后一秒

    // 查询数据库
    const sqlSelect = `
        SELECT * FROM tutem_mall.eb_user_action
        WHERE uid = ? AND peer_uid = ? AND action = ? AND options = ? AND path = ?
        AND add_time BETWEEN ? AND ?
    `;
    const args = [
        uid,
        peer_uid,
        action,
        options_str,
        path,
        dayBegin.getTime() / 1000,
        dayEnd.getTime() / 1000,
    ]; // 转换为UNIX时间戳
    const [rows] = await rds.query(sqlSelect, args);

    if (rows.length > 0) {
        // 如果存在记录，则更新次数
        const rec_id = rows[0].id;
        const sqlUpdate = `UPDATE tutem_mall.eb_user_action SET times = times + 1 WHERE id = ?`;
        await rds.query(sqlUpdate, [rec_id]);
    } else {
        // 如果不存在记录，则插入新记录
        const now = Math.floor(new Date().getTime() / 1000); // 当前时间的UNIX时间戳
        const sqlInsert = `INSERT INTO tutem_mall.eb_user_action (uid, peer_uid, action, path, options, add_time, times) VALUES (?, ?, ?, ?, ?, ?, 1)`;
        await rds.query(sqlInsert, [
            uid,
            peer_uid,
            action,
            path,
            options_str,
            now,
        ]);
    }
}

const task = {
    taskStatusArray,
    taskStatusInfos,
    taskStatusActions,
    taskStatusDescriptions,
    assignTask,
    genTaskMarkdown,
    genTaskText,
    notifyBot,
    notifyTutu,
    notifyXiaoteng,
    notifyWework,
    notifyUserAction,
    recordUserAction,
};

module.exports = task;
